package com.wdb.modules.quartz.rest;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wdb.exception.BadRequestException;
import com.wdb.modules.quartz.domain.QuartzJob;
import com.wdb.modules.quartz.domain.QuartzLog;
import com.wdb.modules.quartz.domain.vo.QuartzJobQueryCriteria;
import com.wdb.modules.quartz.service.QuartzJobService;
import com.wdb.utils.PageResult;
import com.wdb.utils.SpringContextHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.Set;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/8/21 星期三 10:14
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/jobs")
@Api(tags = "系统:定时任务管理")
@Slf4j
public class QuartzJobController {

  private final QuartzJobService quartzJobService;

  @GetMapping
  @ApiOperation("查询任务")
  public ResponseEntity<PageResult<QuartzJob>> queryQuartzJob(
      QuartzJobQueryCriteria criteria, Page<Object> page) {
    return new ResponseEntity<>(quartzJobService.queryAll(criteria, page), HttpStatus.OK);
  }

  @ApiOperation("执行定时任务")
  @PutMapping(value = "/exec/{id}")
  public ResponseEntity<Object> executionQuartzJob(@PathVariable Long id) {
    quartzJobService.execution(quartzJobService.findById(id));
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
  }

  @ApiOperation("更改定时任务状态")
  @PutMapping(value = "/{id}")
  public ResponseEntity<Object> updateQuartzJobStatus(@PathVariable Long id) {
    quartzJobService.updateIsPause(quartzJobService.getById(id));
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
  }

  // 新增定时任务
  @ApiOperation("新增定时任务")
  @PostMapping
  public ResponseEntity<Object> addQuartzJob(@Validated @RequestBody QuartzJob quartzJob) {
    quartzJob.setId(null);
    // 验证Bean是不是合法的
    checkBean(quartzJob.getBeanName());

    quartzJobService.create(quartzJob);
    return new ResponseEntity<>(HttpStatus.CREATED);
  }
  @ApiOperation("修改定时任务")
  @PutMapping
  public ResponseEntity<Object> updateQuartzJob(@Validated @RequestBody QuartzJob quartzJob) {
    // 验证Bean是不是合法的
    checkBean(quartzJob.getBeanName());

    quartzJobService.update(quartzJob);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
  }

  @ApiOperation("删除任务")
  @DeleteMapping
  public  ResponseEntity<Object> deleteQuartJob(@RequestBody Set<Long> ids){
    quartzJobService.delete(ids);
    return new ResponseEntity<>(HttpStatus.OK);
  }

  @ApiOperation("查询任务执行日志")
  @GetMapping(value = "/logs")
  public ResponseEntity<PageResult<QuartzLog>> queryQuartzJobLog(QuartzJobQueryCriteria criteria, Page<Object> page) {
    return new ResponseEntity<>(quartzJobService.queryAllLog(criteria, page), HttpStatus.OK);
  }
  @ApiOperation("导出任务列表")
  @GetMapping("/download")
  public void download(HttpServletResponse response,QuartzJobQueryCriteria criteria) {
       quartzJobService.download(quartzJobService.queryAll(criteria),response);
  }


  /**
   * 检查 Bean 名称的合法性
   *
   * @param beanName 待检查的 Bean 名称，使用了 @NotBlank 注解确保名称不为空
   * @throws BadRequestException 当 Bean 名称不合法时抛出此异常
   */
  private void checkBean(@NotBlank String beanName) throws BadRequestException {
      // 检查 Bean 名称是否包含 '.', 确保名称具有正确的格式
      // if (!beanName.contains(".")) {
      //   throw new BadRequestException("非法的 Bean，请重新输入！");
      // }
      // 检查 Bean 名称是否存在于 Spring 上下文中的所有 Service Bean 名称列表中
      // 这确保了请求的 Bean 是合法且已知的
      if (!SpringContextHolder.getAllServiceBeanName().contains(beanName)) {
        throw new BadRequestException("非法的 Bean，请重新输入！");
      }
  }


}
